<?php
declare (strict_types=1);

namespace app\exam\service\admin;

use app\common\service\BaseService;
use app\exam\logic\admin\{QuestionBank, QuestionDifficult, QuestionPoint};
use app\exam\logic\admin\QuestionTopic as QuestionTopicLogic;
use eduline\admin\libs\pageform\FormItem;
use eduline\admin\libs\pagelist\ListItem;
use eduline\admin\page\PageForm;
use eduline\admin\page\PageList;
use think\annotation\Inject;
use think\facade\Request;

class QuestionTopic extends BaseService
{

    /**
     * @Inject()
     *
     * @var QuestionTopicLogic
     */
    protected $questionTopicLogic;

    /**
     * @Inject()
     *
     * @var QuestionDifficult
     */
    protected $questionDifficult;

    /**
     * @Inject()
     *
     * @var QuestionPoint
     */
    protected $questionPoint;

    /**
     * @Inject()
     *
     * @var QuestionBank
     */
    protected $questionBankLogic;

    /**
     * 题目管理
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/10/29
     *
     * @return mixed
     */
    public function index()
    {
        $map = [];
        // 关键字
        Request::has('title', 'get', true) && $map[] = ['title', 'like', '%' . Request::get('title/s') . '%'];
        // 知识点
        $point = Request::get('point/d', 0);
        $point && $map[] = ['point', 'like', '%,' . $point . ',%'];
        // 题型
        if (Request::has('question_type', 'get', true) && Request::get('question_type/d', -1) !== -1) {
            $map[] = ['question_type', '=', Request::get('question_type/d')];
        }
        // 难易度
        $difficulty = Request::get('difficulty/d', 0);
        $difficulty && $map[] = ['difficulty', '=', $difficulty];

        // 题库
        if (Request::has('bank', 'get', true)) {
            $bank  = Request::get('bank/d');
            $map[] = ['question_bank_id', '=', $bank];
        }

        $data = $this->questionTopicLogic->getList($map)->append(['question_type_text']);
        // 定义字段
        $keyList      = [
            'title'               => ListItem::make('custom')->title('题目名称'),
            'cates'               => ListItem::make()->title('所属分类'),
            'question_bank_title' => ListItem::make()->title('所属题库'),
            'question_type_text'  => ListItem::make()->title('题目类型'),
            'difficulty_title'    => ListItem::make()->title('试题难度'),
            'point_str'           => ListItem::make()->title('知识点'),
            'num'                 => ListItem::make('custom')->title('被引用次数'),
            'answer_num'          => ListItem::make()->title('作答次数'),
            'update_time'         => ListItem::make()->title('更新时间')
        ];
        $questionType = $this->questionTopicLogic->getQuestionTypeOptions();
        $difficulty   = $this->questionDifficult->cascader();
        $point        = $this->questionPoint->cascader();
        // 搜索字段
        $searchKey = [
            'title'         => FormItem::make('input')->title(false)->placeholder('题目名称')->maxlength(30),
            'question_type' => FormItem::make('select')->title(false)->placeholder('题目类型')->options($questionType),
            'bank'          => FormItem::make('custom')->title(false),
            'difficulty'    => FormItem::make('select')->title(false)->placeholder('难易度')->options($difficulty),
            'point'         => FormItem::make('cascader')->title(false)->placeholder('知识点')->options($point),

        ];

        // 设置表单
        $list = new PageList();
        // 表单字段
        $list->pageKey   = $keyList;
        $list->datas     = $data;
        $list->searchKey = $searchKey;

        return $list->send();
    }

    /**
     * 创建试题
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/11/23
     *
     * @return \eduline\admin\page\interfaces\think\Response|\think\Response
     */
    public function create()
    {
        if (Request::isPost()) {
            $data = Request::post();
            $this->questionTopicLogic->createTopic($data);

            return $this->parseToData([], 1, '新建成功');
        }
        $datas = [
            'difficulty'    => $this->questionDifficult->cascader(),
            'question_type' => $this->questionTopicLogic->getQuestionTypeOptions()
        ];
        // 设置表单
        $form              = new PageForm();
        $form->saveMethod  = 'POST';
        $form->savePostUrl = '/exam/admin/question/topic/create';
        $form->datas       = $datas;

        return $form->send();

    }

    /**
     * 编辑题库
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/10/29
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit(int $id)
    {
        if (Request::isPut()) {
            $data = Request::put();
            $this->questionTopicLogic->editTopic($id, $data);

            return $this->parseToData([], 1, '编辑成功');
        }

        // 当前编辑的题目信息
        $data = $this->questionTopicLogic->with(['bankTitleAndCates'])->findOrFail($id);
        // 设置表单
        $form = app(PageForm::class);
        // 表单数据
        $form->datas = $data;
        // 知识点
        $form->point = $this->questionPoint->parseTitle($data->getAttr('point'));
        // 难易度
        $form->difficulty = $this->questionDifficult->cascader();
        // 试题类型
        $form->questionType = $this->questionTopicLogic->getQuestionTypeOptions();
        // 试题答案与选项
        $result = $this->questionTopicLogic->getAnswer($data->getAttr('id'), $data->getAttr('question_type'));
        if (in_array($data->getAttr('question_type'), [6, 7])) {
            $form->options = $result;
            // 答案--单个
            $form->answer = '';
            // 答案--多个
            $form->answers = [];
        } else {
            // 答案--单个
            $form->answer = $result['answer'];
            // 答案--多个
            $form->answers = $result['answers'];
            // 选项
            $form->options = $result['options'];
        }
        $form->saveMethod  = 'PUT';
        $form->savePostUrl = '/exam/admin/question/topic/' . $id . '/edit';

        return $form->send();
    }

    /**
     * 删除题库
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/10/29
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete(int $id)
    {

        $this->questionTopicLogic->deleteTopic($id);

        return $this->parseToData([], 1, '删除成功');
    }

    /**
     * 选择题目面板数据
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/12/17
     *
     * @return \think\Response
     */
    public function chooseOptions()
    {
        $map = [];
        if (input('?get.cate')) {
            $category = input('get.cate/s');
            $map      = [['category', '=', $category]];
        }
        $questionType = $this->questionTopicLogic->getQuestionTypeOptions();
        $difficulty   = $this->questionDifficult->cascader();
        $point        = $this->questionPoint->cascader(0, $map);
        $banks        = $this->questionBankLogic->getBankOptions($map);

        return $this->parseToData([
            'options' => [
                'questionType' => $questionType,
                'difficulty'   => $difficulty,
                'point'        => $point,
                'bank'         => $banks
            ]
        ], 1);
    }

    /**
     * 获取题目列表
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/12/18
     *
     * @return \eduline\admin\page\interfaces\think\Response
     */
    public function getChooseList()
    {
        $map = [];
        // 题库
        Request::has('bank', 'get', true) && $map[] = ['question_bank_id', '=', Request::get('bank/d')];
        // 关键字
        Request::has('title', 'get', true) && $map[] = ['title', 'like', '%' . Request::get('title/s') . '%'];
        // 知识点
        $point = Request::get('point/d', 0);
        $point && $map[] = ['point', 'like', '%,' . $point . ',%'];
        // 题型
        if (Request::has('question_type', 'get', true) && Request::get('question_type/d', -1) !== -1) {
            $map[] = ['question_type', '=', Request::get('question_type/d')];
        }
        // 难易度
        $difficulty = Request::get('difficulty/d', 0);
        $difficulty && $map[] = ['difficulty', '=', $difficulty];
        // 
        if (input('?get.cate')) {
            $category = input('get.cate/s');
            // 对应分类题库
            $binkIds = $this->questionBankLogic->where('category', $category)->column('id');
            $map[]   = ['question_bank_id', 'IN', $binkIds];
        }

        $data = $this->questionTopicLogic->getChooseList($map);
        // 设置表单
        $list = new PageList();
        // 表单字段
        $list->datas = $data;

        return $list->send();
    }

    /**
     * 获取单题的详情
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/2/5
     *
     * @param int $id
     * @return \think\Response
     */
    public function info(int $id)
    {
        $data = $this->questionTopicLogic->with(['questionBankTitle', 'difficultyTitle'])->findOrFail($id)->append(['question_type_text']);
        $this->questionTopicLogic->paddingTopicData($data);

        return BaseService::parseToData($data, 1);
    }
}